import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, Bell, TestTube, CheckCircle, AlertCircle, Clock, Settings } from 'lucide-react';
import NotificationService from '../services/notificationService';
import { notificationAPI } from '../services/notificationAPI';

interface TestResult {
  name: string;
  status: 'pending' | 'success' | 'error';
  message: string;
  timestamp: Date;
}

export default function NotificationTestPage() {
  const navigate = useNavigate();
  const [testResults, setTestResults] = useState<TestResult[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [permission, setPermission] = useState<NotificationPermission>('default');

  const notificationService = NotificationService.getInstance();

  useEffect(() => {
    const currentPermission = notificationService.getPermissionStatus();
    setPermission(currentPermission);
  }, []);

  const addTestResult = (name: string, status: 'success' | 'error' | 'pending', message: string) => {
    setTestResults(prev => [...prev, {
      name,
      status,
      message,
      timestamp: new Date()
    }]);
  };

  const clearResults = () => {
    setTestResults([]);
  };

  // 测试1: 权限请求
  const testPermissionRequest = async () => {
    try {
      const newPermission = await notificationService.requestPermission();
      setPermission(newPermission);
      
      if (newPermission === 'granted') {
        addTestResult('权限请求', 'success', '通知权限已成功授予');
      } else {
        addTestResult('权限请求', 'error', `权限被拒绝: ${newPermission}`);
      }
    } catch (error) {
      addTestResult('权限请求', 'error', `权限请求失败: ${error}`);
    }
  };

  // 测试2: 基础通知
  const testBasicNotification = async () => {
    try {
      await notificationService.showNotification('测试通知', {
        body: '这是一个基础测试通知',
        tag: 'basic-test'
      });
      addTestResult('基础通知', 'success', '基础通知发送成功');
    } catch (error) {
      addTestResult('基础通知', 'error', `基础通知发送失败: ${error}`);
    }
  };

  // 测试3: 带操作的通知
  const testActionNotification = async () => {
    try {
      await notificationService.showNotification('操作通知测试', {
        body: '这是一个带操作按钮的通知',
        tag: 'action-test',
        requireInteraction: true,
        actions: [
          { action: 'confirm', title: '确认', icon: '/icon-192x192.png' },
          { action: 'cancel', title: '取消', icon: '/icon-192x192.png' }
        ]
      });
      addTestResult('操作通知', 'success', '带操作的通知发送成功');
    } catch (error) {
      addTestResult('操作通知', 'error', `操作通知发送失败: ${error}`);
    }
  };

  // 测试4: 后端API连接
  const testBackendAPI = async () => {
    try {
      const settings = await notificationAPI.getSettings();
      addTestResult('后端API', 'success', `成功获取通知设置: ${JSON.stringify(settings)}`);
    } catch (error) {
      addTestResult('后端API', 'error', `后端API连接失败: ${error}`);
    }
  };

  // 测试5: 设置更新
  const testSettingsUpdate = async () => {
    try {
      const updatedSettings = await notificationAPI.updateSettings({
        task_reminders: true,
        sound_enabled: false
      });
      addTestResult('设置更新', 'success', `设置更新成功: ${JSON.stringify(updatedSettings)}`);
    } catch (error) {
      addTestResult('设置更新', 'error', `设置更新失败: ${error}`);
    }
  };

  // 测试6: 每日总结
  const testDailySummary = async () => {
    try {
      const summary = await notificationAPI.getDailySummary();
      addTestResult('每日总结', 'success', `每日总结获取成功: ${JSON.stringify(summary)}`);
    } catch (error) {
      addTestResult('每日总结', 'error', `每日总结获取失败: ${error}`);
    }
  };

  // 测试7: Service Worker
  const testServiceWorker = async () => {
    try {
      if ('serviceWorker' in navigator) {
        const registration = await navigator.serviceWorker.getRegistration();
        if (registration) {
          addTestResult('Service Worker', 'success', 'Service Worker 已注册并运行');
        } else {
          addTestResult('Service Worker', 'error', 'Service Worker 未注册');
        }
      } else {
        addTestResult('Service Worker', 'error', '浏览器不支持 Service Worker');
      }
    } catch (error) {
      addTestResult('Service Worker', 'error', `Service Worker 检测失败: ${error}`);
    }
  };

  // 运行所有测试
  const runAllTests = async () => {
    setIsRunning(true);
    clearResults();

    const tests = [
      { name: '权限请求', fn: testPermissionRequest },
      { name: '基础通知', fn: testBasicNotification },
      { name: '操作通知', fn: testActionNotification },
      { name: '后端API', fn: testBackendAPI },
      { name: '设置更新', fn: testSettingsUpdate },
      { name: '每日总结', fn: testDailySummary },
      { name: 'Service Worker', fn: testServiceWorker }
    ];

    for (const test of tests) {
      addTestResult(test.name, 'pending', '测试进行中...');
      await test.fn();
      await new Promise(resolve => setTimeout(resolve, 500)); // 短暂延迟
    }

    setIsRunning(false);
  };

  const getStatusIcon = (status: TestResult['status']) => {
    switch (status) {
      case 'success':
        return <CheckCircle className="w-5 h-5 text-green-600" />;
      case 'error':
        return <AlertCircle className="w-5 h-5 text-red-600" />;
      case 'pending':
        return <Clock className="w-5 h-5 text-yellow-600" />;
    }
  };

  const getStatusColor = (status: TestResult['status']) => {
    switch (status) {
      case 'success':
        return 'bg-green-50 border-green-200';
      case 'error':
        return 'bg-red-50 border-red-200';
      case 'pending':
        return 'bg-yellow-50 border-yellow-200';
    }
  };

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* Header */}
      <header className="sticky top-0 bg-theme-bg/95 backdrop-blur-sm shadow-sm border-b border-theme-border/60 z-10">
        <div className="flex items-center justify-between px-4 py-3 max-w-md mx-auto">
          <button
            onClick={() => navigate(-1)}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">通知功能测试</h1>
          <div className="w-9 h-9" />
        </div>
      </header>

      <main className="px-4 py-6 space-y-4 max-w-md mx-auto">
        {/* 权限状态 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-4">
          <div className="flex items-center gap-3">
            <Bell className={`w-6 h-6 ${permission === 'granted' ? 'text-green-600' : 'text-red-600'}`} />
            <div>
              <h3 className="font-semibold text-theme-text">通知权限状态</h3>
              <p className={`text-sm ${permission === 'granted' ? 'text-green-600' : 'text-red-600'}`}>
                {permission === 'granted' ? '已授权' : permission === 'denied' ? '已拒绝' : '未设置'}
              </p>
            </div>
          </div>
        </div>

        {/* 测试控制 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-4">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <TestTube className="w-5 h-5 text-blue-600" />
              <h3 className="font-semibold text-theme-text">功能测试</h3>
            </div>
            <button
              onClick={clearResults}
              className="text-sm text-theme-text-muted hover:text-theme-text-secondary"
            >
              清除结果
            </button>
          </div>

          <div className="space-y-3">
            <button
              onClick={runAllTests}
              disabled={isRunning}
              className="w-full px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 
                       disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
            >
              {isRunning ? '测试进行中...' : '运行全部测试'}
            </button>

            <div className="grid grid-cols-2 gap-2">
              <button
                onClick={testPermissionRequest}
                disabled={isRunning}
                className="px-3 py-2 bg-theme-bg-tertiary text-theme-text-secondary rounded-lg hover:bg-slate-200 
                         disabled:opacity-50 text-sm transition-colors"
              >
                权限测试
              </button>
              <button
                onClick={testBasicNotification}
                disabled={isRunning || permission !== 'granted'}
                className="px-3 py-2 bg-theme-bg-tertiary text-theme-text-secondary rounded-lg hover:bg-slate-200 
                         disabled:opacity-50 text-sm transition-colors"
              >
                基础通知
              </button>
              <button
                onClick={testBackendAPI}
                disabled={isRunning}
                className="px-3 py-2 bg-theme-bg-tertiary text-theme-text-secondary rounded-lg hover:bg-slate-200 
                         disabled:opacity-50 text-sm transition-colors"
              >
                API测试
              </button>
              <button
                onClick={testServiceWorker}
                disabled={isRunning}
                className="px-3 py-2 bg-theme-bg-tertiary text-theme-text-secondary rounded-lg hover:bg-slate-200 
                         disabled:opacity-50 text-sm transition-colors"
              >
                SW测试
              </button>
            </div>
          </div>
        </div>

        {/* 测试结果 */}
        {testResults.length > 0 && (
          <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-4">
            <h3 className="font-semibold text-theme-text mb-4">测试结果</h3>
            <div className="space-y-3">
              {testResults.map((result, index) => (
                <div
                  key={index}
                  className={`p-3 rounded-lg border ${getStatusColor(result.status)}`}
                >
                  <div className="flex items-start gap-3">
                    {getStatusIcon(result.status)}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between">
                        <h4 className="font-medium text-theme-text">{result.name}</h4>
                        <span className="text-xs text-theme-text-muted">
                          {result.timestamp.toLocaleTimeString()}
                        </span>
                      </div>
                      <p className="text-sm text-theme-text-secondary mt-1 break-words">
                        {result.message}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 快捷操作 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-4">
          <h3 className="font-semibold text-theme-text mb-4">快捷操作</h3>
          <div className="space-y-2">
            <button
              onClick={() => navigate('/notifications')}
              className="w-full flex items-center gap-3 p-3 text-left hover:bg-theme-bg-secondary 
                       rounded-lg transition-colors"
            >
              <Settings className="w-5 h-5 text-blue-600" />
              <span className="font-medium text-theme-text">打开通知设置</span>
            </button>
          </div>
        </div>

        {/* 说明信息 */}
        <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
          <h4 className="font-semibold text-blue-800 mb-2">使用说明</h4>
          <ul className="text-sm text-blue-700 space-y-1">
            <li>• 首次使用需要授权通知权限</li>
            <li>• 测试通知会在几秒后自动消失</li>
            <li>• API测试需要后端服务运行</li>
            <li>• Service Worker 提供离线通知支持</li>
          </ul>
        </div>
      </main>
    </div>
  );
}
